<template>
  <el-upload
    ref="fileUpload"
    :action="uploadFileUrl"
    :headers="headers"
    :show-file-list="false"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    style="display: inline-block"
  >
    <slot></slot>
  </el-upload>
</template>

<script setup lang="ts">
import { defineEmits, PropType, reactive, toRefs, ref } from "vue";
import Auth from "@/api/Auth";
import { ElMessage } from "element-plus";
const uploadFileUrl = ref("/dev-api/file/uploadMultipartFile"); // 上传文件服务器地址
const dskey = Auth.getLocal("dskey");
const headers = ref({
  Authorization: "Bearer " + Auth.getToken(),
  dsKey: dskey,
});
import MessageType from "@/utils/MessageType";
const props = defineProps({
  fileTypes: {
    type: Array,
    required: true,
    default: null,
  },
  isImg: {
    type: Boolean,
    required: true,
    default: true,
  },
});
const beforeUpload = (file: any) => {
  const suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
  const suffixes = props.fileTypes;
  const len = suffixes.filter((item) => {
    return item === suffix.toLowerCase();
  }).length;
  if (len === 0) {
    ElMessage.error("不支持的文件类型,仅支持：" + suffixes.join(","));
  }
  return len > 0;
};
const type1 = ["png", "jpg", "jpeg", "gif"];
const type2 = ["doc", "docx", "xls", "xlsx", "pdf", "zip", "rar"];

const emits = defineEmits(["uploadSuccess"]);
//上传成功回调
const handleSuccess = (res: any) => {
  console.log("文件上传成功", res);
  // text: "0",image: "1",file: "2",voice: "3",
  const fileType = res.fileType && res.fileType.split(".")[1];
  console.log("fileType", fileType);

  let type = "";
  if (type1.includes(fileType)) {
    type = MessageType.image + "";
  } else if (type2.includes(fileType)) {
    type = MessageType.file + "";
  }
  console.log("文件上传", res, type);

  emits("uploadSuccess", res, type);
};
// const { host } = toRefs(vimData);
</script>

<style scoped></style>
